﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using DevExpress.XtraPrinting;

namespace ReportGenerators.Khac
{
    public partial class FrmThongKeChiTietTheoTaiKhoan : BasicForms.FrmSupportPrintableComponents
    {
        public FrmThongKeChiTietTheoTaiKhoan()
        {
            InitializeComponent();
        }

        private void FrmThongKeChiTietTheoTaiKhoan_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            cmbTaiKhoan.DataSource = DanhMucTaiKhoan.Instance.DataView;
            cmbTaiKhoan.DisplayColumn = "SoHieu";
            cmbTaiKhoan.ValueColumn = "ID";
            cmbTaiKhoan.AddVisibleColumn("SoHieu", "Số hiệu", 100, 1);
            cmbTaiKhoan.AddVisibleColumn("Ten", "Tên", 300, 2);
            cmbTaiKhoan.EditValue = Guid.Empty;

            cmbDoiTuongNghiepVu.DataSource = DanhMucDoiTuongNghiepVu.Instance.DataView;
            cmbDoiTuongNghiepVu.DisplayColumn = "Ma";
            cmbDoiTuongNghiepVu.ValueColumn = "ID";
            cmbDoiTuongNghiepVu.AddVisibleColumn("Ma", "Mã", 100, 1);
            cmbDoiTuongNghiepVu.AddVisibleColumn("Ten", "Tên", 300, 2);
            cmbDoiTuongNghiepVu.EditValue = Guid.Empty;


            cmbKyBaoCao.SelectedIndex = 19;

            gridControl.DataSource = dsThongKeChiTheoTaiKhoan.Detail;
            FormatNumberInGridView(gridView);
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                if(column.Name != "colSo" || column.Name != "colTenDoiTuongNghiepVu")
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }
        }

        private void cmbTaiKhoan_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbTaiKhoan.EditValue = Guid.Empty;
           
        }
        private void cmbDoiTuongNghiepVu_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbDoiTuongNghiepVu.EditValue = Guid.Empty;
        }
        private void cmbTaiKhoan_EditValueChanged(object sender, EventArgs e)
        {
            if (cmbTaiKhoan.EditValue is Guid &&  (Guid)cmbTaiKhoan.EditValue != Guid.Empty)
            {
                TaiKhoan selectedTaiKhoan = DanhMucTaiKhoan.Instance.GetByID((Guid)cmbTaiKhoan.EditValue);
                if (selectedTaiKhoan.SoHieu.StartsWith("11"))
                {
                    foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                    {
                        switch (column.Name)
                        {
                            case "colPhatSinhNo":
                                column.Caption = "Thu";
                                break;
                            case "colPhatSinhCo":
                                column.Caption = "Chi";
                                break;
                            case "colDuNo":
                                column.Caption = "Dư";
                                break;
                            case "colDuCo":
                                column.Caption = "Bị âm";
                                break;
                        }
                    }
                }
                else if (selectedTaiKhoan.SoHieu.StartsWith("131"))
                {
                    foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                    {
                        switch (column.Name)
                        {
                            case "colPhatSinhNo":
                                column.Caption = "Tăng phải thu";
                                break;
                            case "colPhatSinhCo":
                                column.Caption = "Giảm phải thu";
                                break;
                            case "colDuNo":
                                column.Caption = "Phải thu";
                                break;
                            case "colDuCo":
                                column.Caption = "Bị âm";
                                break;
                        }
                    }
                }
                else if (selectedTaiKhoan.SoHieu.StartsWith("331"))
                {
                    foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                    {
                        switch (column.Name)
                        {
                            case "colPhatSinhNo":
                                column.Caption = "Giảm phải trả";
                                break;
                            case "colPhatSinhCo":
                                column.Caption = "Tăng phải trả";
                                break;
                            case "colDuNo":
                                column.Caption = "";
                                break;
                            case "colDuCo":
                                column.Caption = "Phải trả";
                                break;
                        }
                    }
                }
                else
                {
                    foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                    {
                        switch (column.Name)
                        {
                            case "colPhatSinhNo":
                                column.Caption = "PS Nợ";
                                break;
                            case "colPhatSinhCo":
                                column.Caption = "PS Có";
                                break;
                            case "colDuNo":
                                column.Caption = "Dư nợ";
                                break;
                            case "colDuCo":
                                column.Caption = "Dư có";
                                break;
                        }
                    }
                }
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            Guid taiKhoanID = Guid.Empty;
            if (cmbTaiKhoan.EditValue is Guid && (Guid)cmbTaiKhoan.EditValue != Guid.Empty)   taiKhoanID = (Guid)cmbTaiKhoan.EditValue;
            else
            {
                MessageBox.Show("Chọn tài khoản");
                cmbTaiKhoan.Focus();
                return;
            }

            Guid doiTuongNghiepVuID = Guid.Empty;
            if (cmbDoiTuongNghiepVu.EditValue is Guid && (Guid)cmbDoiTuongNghiepVu.EditValue != Guid.Empty)   doiTuongNghiepVuID = (Guid)cmbDoiTuongNghiepVu.EditValue;
           

            BasicForms.FrmProgressBarDev.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;
                cmd.CommandText = string.Format("SELECT B.ChungTuID, B.NgayGhiSo, B.So, B.Ngay, A.DienGiai, C.SoHieu TaiKhoanDoiUng, E.Ten TenDoiTuongNghiepVu,\n" +
                                                    "   SUM(A.GiaTri) PhatSinhNo, CAST(0 AS decimal) PhatSinhCo, CAST(0 AS decimal) SoDuNo, CAST(0 AS decimal) SoDuCo \n" +
                                                    "FROM ButToan A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuID \n" +
                                                    "		INNER JOIN TaiKhoan C ON A.TaiKhoanCoID = C.ID \n" +
                                                    "		INNER JOIN GhiNo D ON A.ID = D.ButToanID \n" +
                                                    "       INNER JOIN DoiTuongNghiepVu E ON A.DoiTuongNghiepVuNoID = E.ID \n" +
                                                    "WHERE D.TaiKhoanID = '{0}' AND (A.DoiTuongNghiepVuNoID = '{1}' OR '{1}' =  '{2}') \n" +
                                                    "           AND @NgayBatDau < A.Ngay AND A.Ngay <= @NgayKetThuc \n" +
                                                    "GROUP BY B.ChungTuID, B.NgayGhiSo, B.So, B.Ngay, A.DienGiai, C.SoHieu,E.Ten  \n" +
                                                    "HAVING SUM(A.GiaTri) >0 \n" +
                                                    "UNION \n" +
                                                    "SELECT B.ChungTuID, B.NgayGhiSo, B.So, B.Ngay, A.DienGiai, C.SoHieu TaiKhoanDoiUng, E.Ten TenDoiTuongNghiepVu,\n" +
                                                    "		 CAST(0 AS decimal) PhatSinhNo, SUM(A.GiaTri) PhatSinhCo, CAST(0 AS decimal) SoDuNo, CAST(0 AS decimal) SoDuCo \n" +
                                                    "FROM ButToan A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuID \n" +
                                                    "		INNER JOIN TaiKhoan C ON A.TaiKhoanNoID = C.ID \n" +
                                                    "		INNER JOIN GhiCo D ON A.ID = D.ButToanID \n" +
                                                    "       INNER JOIN DoiTuongNghiepVu E ON A.DoiTuongNghiepVuCoID = E.ID \n" +
                                                    "WHERE  D.TaiKhoanID = '{0}' AND (A.DoiTuongNghiepVuCoID = '{1}' OR '{1}' =  '{2}') \n" +
                                                    "           AND @NgayBatDau < A.Ngay AND A.Ngay <= @NgayKetThuc \n" +
                                                    "GROUP BY B.ChungTuID, B.NgayGhiSo, B.So, B.Ngay, A.DienGiai, C.SoHieu,E.Ten  \n" +
                                                    "HAVING SUM(A.GiaTri) >0 \n" +
                                                    "ORDER BY B.Ngay \n",
                                                    taiKhoanID, doiTuongNghiepVuID, Guid.Empty);
                cmd.Parameters.AddWithValue("NgayBatDau", dtNgayBatDau.DateTime);
                cmd.Parameters.AddWithValue("NgayKetThuc", dtNgayKetThuc.DateTime);

                dsThongKeChiTheoTaiKhoan.Detail.Clear();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dsThongKeChiTheoTaiKhoan.Detail);

                SoDuTaiKhoan soDuBanDau = null;
                if (doiTuongNghiepVuID != Guid.Empty)
                    soDuBanDau = SoDuTaiKhoan.CalculateFromDB(cmd, dtNgayBatDau.DateTime, taiKhoanID, doiTuongNghiepVuID);
                else
                    soDuBanDau = SoDuTaiKhoan.CalculateFromDB(cmd, dtNgayBatDau.DateTime, taiKhoanID);
                
                decimal duNoLuyKe = soDuBanDau.DuNo;
                decimal duCoLuyKe = soDuBanDau.DuCo;
                foreach (DataRow row in dsThongKeChiTheoTaiKhoan.Detail.Rows)
                {
                    if (row["PhatSinhNo"] != DBNull.Value) duNoLuyKe += (decimal)row["PhatSinhNo"];
                    if (row["PhatSinhCo"] != DBNull.Value) duCoLuyKe += (decimal)row["PhatSinhCo"];
                    if (duNoLuyKe >= duCoLuyKe)
                    {
                        duNoLuyKe = duNoLuyKe - duCoLuyKe;
                        duCoLuyKe = 0;
                    }
                    else
                    {
                        duCoLuyKe = duCoLuyKe - duNoLuyKe;
                        duNoLuyKe = 0;
                    }
                    row["SoDuNo"] = duNoLuyKe;
                    row["SoDuCo"] = duCoLuyKe;
                }

                DataRow rowBanDau = dsThongKeChiTheoTaiKhoan.Detail.NewRow();
                rowBanDau["Ngay"] = dtNgayBatDau.DateTime;
                rowBanDau["So"] = "";
                rowBanDau["NgayGhiSo"] = dtNgayBatDau.DateTime;
                rowBanDau["DienGiai"] = "Đầu kỳ báo cáo";
                rowBanDau["SoDuNo"] = soDuBanDau.DuNo;
                rowBanDau["SoDuCo"] = soDuBanDau.DuCo;
                dsThongKeChiTheoTaiKhoan.Detail.Rows.InsertAt(rowBanDau, 0);
                
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void gridView_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                ArrayList arEditChungTu = new ArrayList();
                foreach (int index in gridView.GetSelectedRows())
                {
                    Guid chungTuID = (Guid)gridView.GetDataRow(index)["ChungTuID"];
                    arEditChungTu.Add(chungTuID);
                }
                foreach (Guid chungTuID in arEditChungTu)
                {
                    //RaiseEventRequestEditChungTu(chungTuID);
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            string option1 = string.Format("Tài khoản: {0}", DanhMucTaiKhoan.Instance.GetByID((Guid)cmbTaiKhoan.EditValue).SoHieu);

            string option2 = "";
            if (cmbDoiTuongNghiepVu.EditValue is Guid && (Guid)cmbDoiTuongNghiepVu.EditValue != Guid.Empty) option2 = string.Format("Đối tượng: {0}",
                DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuongNghiepVu.EditValue).Ten);

            PrintWithHeader(true, gridControl, true, true, "Thống kê chi tiết theo tài khoản", option1, option2);
        }
    }
}
